import React, { useState, useEffect, useRef } from "react";
import { Space, Table, Image, Button, Popconfirm, Spin } from "antd";
import { getBannerList, deleteBannerById } from "@/api/banner";
import { useSize } from "ahooks";
import usePagination from "@/hooks/usePagination";
import { DeleteOutlined } from "@ant-design/icons";

export default function List() {
  const [loading, setLoading] = useState(true);
  // 实现选择删除
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const onSelectChange = (newSelectedRowKeys) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const flagRef = useRef(true);

  // 调用自定义的分页hook
  const pagination = usePagination({
    callback() {
      flagRef.current = true;
    },
  });
  const [list, setList] = useState([]);

  // 获取banner列表
  const getBannerListData = () => {
    getBannerList()
      .then((res) => {
        setList(res.data.data);
        if (
          res.data.data.length <=
          pagination.pageSize * (pagination.current - 1)
        ) {
          flagRef.current = false;
        }
      })
      .finally(() => setLoading(false));
  };

  // 批量删除banner
  const deleteBannerByIdData = (params) => {
    deleteBannerById(params).then((res) => {
      getBannerList(res);
    });
  };

  // 组件挂载时获取数据
  useEffect(() => {
    getBannerListData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 用usesize来获取Table的宽高
  const size = useSize(document.querySelector("body"));
  const defaultHeight = document.body.offsetHeight;

  return (
    <Spin tip="Loading" size="small" spinning={loading}>
      <Space direction="vertical">
        {selectedRowKeys.length > 0 ? (
          // 实现选择删除
          <Button
            type="primary"
            size="large"
            onClick={() => {
              deleteBannerByIdData({ bannerid: selectedRowKeys });
              getBannerListData();
            }}
          >
            删除选中项
          </Button>
        ) : (
          <Button disabled type="primary" size="large">
            X X X X
          </Button>
        )}
        <Table
          style={{ width: "99%" }}
          dataSource={list} // 数据源
          rowKey={(record) => record.bannerid}
          scroll={{
            y: (size ? size.height : defaultHeight) - 320, //窗口自适应
          }}
          pagination={pagination} //分页
          rowSelection={rowSelection} //实现选择删除
        >
          <Table.Column
            title="序号"
            render={(_, record, index) => {
              return (
                <span>
                  {pagination.pageSize *
                    (flagRef.current
                      ? pagination.current - 1
                      : pagination.current - 2) +
                    index +
                    1}
                </span>
              );
            }}
          ></Table.Column>
          <Table.Column
            title="图片"
            dataIndex={"img"}
            render={(text) => {
              return <Image src={text} style={{ height: 100 }} />;
            }}
          ></Table.Column>
          <Table.Column title="详情" dataIndex={"alt"}></Table.Column>
          <Table.Column title="链接" dataIndex={"link"}></Table.Column>
          <Table.Column
            title="操作"
            render={(_, record) => {
              return (
                <Popconfirm
                  title="警告警告警告"
                  description="确定要删除吗?"
                  onConfirm={() => {
                    deleteBannerById({ bannerid: record.bannerid }).then(() => {
                      console.log("删除成功");
                      getBannerListData();
                    });
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    type="danger"
                    shape="circle"
                    icon={<DeleteOutlined />}
                  ></Button>
                </Popconfirm>
              );
            }}
          ></Table.Column>
        </Table>
      </Space>
    </Spin>
  );
}
